package com.chap17.completablefuture;

import lombok.extern.slf4j.Slf4j;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * <code>Demo15</code>
 * </p>
 *
 * @author junbao3
 * TODO
 * @date 2023-05-10 14:28
 * Copyright (C) 2021 IFlyTek. All rights reserved.
 */
@Slf4j
public class Demo15 {
    public static void main(String[] args) {
        CompletableFuture.supplyAsync(()->{
            int num = new Random().nextInt(10);
            log.debug("第一阶段start："+num);
            sleep(num, TimeUnit.SECONDS);
            log.debug("第一阶段end："+num);
            return num;
        }).applyToEither(CompletableFuture.supplyAsync(()->{
            int num = new Random().nextInt(10);
            log.debug("第二阶段start："+num);
            sleep(num, TimeUnit.SECONDS);
            log.debug("第二阶段end："+num);
            return num;
        }),(num)->{
            log.debug("最快的结果：{}",num);
            return num*2;
        }).join();
    }

    private static void sleep(int num, TimeUnit seconds) {
        try {
            seconds.sleep(num);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
